<template>
    <div class="container">
        <div slot="tip" class="el-upload__tip">只可上传一个，格式可支持PDF、word、excel，大小不限</div>
      <el-upload
        :class="{hide: !isShowUpload}"
        :action="action"
        :before-upload="handleBeforeUpload"
        :on-remove="handleRemove"
        :on-exceed="handleExceed"
        :on-success="handleSuccess"
        :on-error="handleError"
        :limit="1"
        :file-list="fileList"
        multiple
      >
        <!-- <el-button size="small" type="primary">选择文件</el-button> -->
        <el-button slot="trigger" type="primary" size="small" icon="el-icon-plus">点击上传</el-button>
      </el-upload>
    </div>
</template>

<script>
import { UploadOption, ResponseCode } from '@/config/constants'
import { getToken } from '@/utils/auth'
import { fileTokenKey } from '@/config/settings'

export default {
    name: 'UploadFIle',
    props: {
        value: {
            type: [String, Array],
            default: ''
        }
    },
    data() {
        return {
            action: UploadOption.ACTION,
            headers: {
                [fileTokenKey]: getToken()
            },
            fileList: [],
            files: [],
            isShowUpload: true,
        }
    },
    watch: {
        value(val) {
            if (val) {
                try {
                    if (Array.isArray(val)) {
                        this.files = val
                        this.fileList = val
                        this.uploadBtnShow(this.files)
                    }
                } catch (error) {
                    console.log(error)
                }
            }
        }
    },
    methods: {
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
        },
        handleRemove(file) {
            console.log(this.files, file, this.fileList)
            this.files.some((item, index) => {
                if (item.uid === file.uid) {
                    this.files.splice(index, 1)
                    return true
                }
            })
            this.uploadBtnShow(this.files)
            this.$emit('update:value', this.getFileList())
        },
        handleSuccess(response, file, fileList) {
            if (response.code === ResponseCode.success) {
                this.files = fileList
                this.uploadBtnShow(this.files)
                this.$emit('update:value', this.getFileList())
            } else {
                fileList.some((item, index) => {
                    if (item.uid === file.uid) {
                        fileList.splice(index, 1)
                        return true
                    }
                })
                this.$message.error('文件上传失败，请重试！')
            }
        },
        handleError() {
            this.$message.error('网络异常，请稍后再试!')
        },
        getFileList() {
            const data = this.files.map((item) => {
                return {
                    name: item.name,
                    url: item.response.data.objectUrl
                }
            })
            return data
        },
        handleBeforeUpload(file) {
            const fileArr = ['xls', 'xlsx', 'doc', 'docx', 'pdf']
            const FILE_NAME = file.name
            if (!fileArr.includes(FILE_NAME.split('.').pop())) {
                this.$message.warning('仅支持PDF、word、excel文件')
                return false
            }
            return true
        },
        uploadBtnShow(fileList) {
            this.isShowUpload = !(fileList.length >= 1)
        }
    },
}
</script>

<style scoped lang="scss">
.hide ::v-deep .el-button.el-button--small {
    display: none;
}
.el-upload__tip {
    margin: 0;
    color: #aaa;
}
</style>
